//
//  ShowWorksViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 9/20/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ShowWorksViewController.h"
#import "WorksCell.h"
#import "WorksDetailViewController.h"
#import "CHTCollectionViewWaterfallLayout.h"
@interface ShowWorksViewController ()
{
    UILabel * tmpLabel;
    NSArray * colorArray;
}
@end

@implementation ShowWorksViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    page = 1;
    SceneID = [[NSString alloc] initWithFormat:@"%@",@""];
    dataArray = [[NSMutableArray alloc] init];
    sceneArray = [[NSMutableArray alloc] init];
    SceneName = [[NSString alloc] init];
    isfirst = YES;
    canaddmore = YES;
    colorArray = @[UIColorFromRGB(0x826c6c),UIColorFromRGB(0x82786c),UIColorFromRGB(0x7b946a),UIColorFromRGB(0x5f777d),UIColorFromRGB(0x80697a)];
    self.titleLabel.text = @"选择年龄";
    
    sceneBtn = [self createButtonOnNavigationWithRect:CGRectMake(120, 0, 320-240, 44) normalImg:nil highlightImg:nil];
    sceneBtn.backgroundColor = [UIColor clearColor];
    [sceneBtn addTarget:self action:@selector(chooseScene) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:sceneBtn];
    
    CGFloat cheight = IOS7?20:0;
    titleIV = [UIImageView initImageViewRect:CGRectMake(410/2.0f-6-2, (44-4)/2.0f+cheight, 8,4) andImage:LOADIMAGE(@"downsanjiao_dark@2x") andUserInteractionEnabled:YES];
    [self.navigationBarView addSubview:titleIV];
    
    
    [self initViews];
    [self getListDatas:page];
    
}

#pragma mark
#pragma mark UI布局
-(void)initViews
{
//    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    flowLayout.minimumInteritemSpacing = 0;
//    flowLayout.minimumLineSpacing = 3;
//    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    testLB = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 145, 15)];
    testLB.numberOfLines = 0;
    testLB.font = [UIFont systemFontOfSize:15];
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(3,3,3,3);
    layout.minimumInteritemSpacing=3;
    
    mCollectionView = [[UICollectionView alloc] initWithFrame:self.contentView.bounds collectionViewLayout:layout];
    [mCollectionView registerClass:[WorksCell class] forCellWithReuseIdentifier:@"cell"];
    mCollectionView.backgroundColor= mClearColor;
    mCollectionView.alwaysBounceVertical = YES;
    mCollectionView.showsVerticalScrollIndicator = NO;
    mCollectionView.delegate = self;
    mCollectionView.dataSource = self;
    [self.contentView addSubview:mCollectionView];
    [mCollectionView addFooterWithTarget:self action:@selector(footerPulltoRefreshData)];
    [mCollectionView addHeaderWithTarget:self action:@selector(heaererPulltoRefreshData)];
    
//    filterView = [[FilterView alloc] initWithFrame:self.view.frame];
//    filterView.delegate = self;
//    [self.view addSubview:filterView];
//    [filterView hiddenTheView];
    
    mScreenView = [[ScreenView alloc] initWithFrame:self.contentView.bounds];
    mScreenView.delegate = self;
    [self.contentView addSubview:mScreenView];
    [mScreenView hiddenTheScreenView];
    
}

#pragma mark  =======上下拉刷新========
-(void)heaererPulltoRefreshData
{
    page = 1;
    [self getListDatas:1];
}

-(void)footerPulltoRefreshData
{
    if (1) {
        page++;
        [self getListDatas:page];
    }else{
        if (1) {
            mCollectionView.footerRefreshingText = @"没有更多数据...";
            [self performSelector:@selector(delayToEndRefreshLoading) withObject:nil afterDelay:.5f];
        }
    }
}
-(void)delayToEndRefreshLoading
{
    [mCollectionView footerEndRefreshing];
    mCollectionView.footerRefreshingText = @"正在加载数据";
}

#pragma mark
#pragma mark UIScroolView Delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    DDLOG(@"mCollectionView.contentOffset.y = %f",mCollectionView.contentOffset.y);
    if (scrollView == mCollectionView){
        if (canaddmore){
            if([dataArray count]<6){
                return;
            }
            if (mCollectionView.contentSize.height-mCollectionView.contentOffset.y<800){
                page++;
                DDLOG_CURRENT_METHOD;
                DDLOG(@"page = %d",page);
                [self getListDatas:page];
                canaddmore =NO;
            }
            
        }
    }
}

#pragma mark
#pragma mark UICollectionView Delegate
//设置分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个分区上的元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [dataArray count];
}

//设置元素内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    WorksCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    cell.dataDict = [dataArray objectAtIndex:indexPath.row];
    cell.imageIV.backgroundColor = [colorArray objectAtIndex:indexPath.row%5];
    return cell;
}

////设置元素的的大小框
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    UIEdgeInsets top ={3,3,3,3};
//    return top;
//}

//设置顶部的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={0,0};
    return size;
}

//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    testLB.frame = CGRectMake(0, 0, 145, 15);
    testLB.text = dataArray[indexPath.row][@"WDesc"];
    [testLB sizeToFit];
    
    if (testLB.frame.size.height > 55) {
        testLB.frame = CGRectMake(0, 0, 145, 55);
        return CGSizeMake(155.5,[dataArray[indexPath.row][@"PhotoHeight"] floatValue]/2.0f+5+testLB.frame.size.height+5+40);
    }
    
    return CGSizeMake(155.5,[dataArray[indexPath.row][@"PhotoHeight"] floatValue]/2.0f+5+testLB.frame.size.height+5+40);
}

//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dict = [dataArray objectAtIndex:indexPath.row];
    WorksDetailViewController * detailVC = [[WorksDetailViewController alloc] init];
    detailVC.SeriesName = dict[@"SeriesName"];
    detailVC.SeriesID = dict[@"SeriesID"];
    detailVC.EmplID = dict[@"EmplID"];
    detailVC.SceneID = dict[@"SceneID"];
    
    for (NSDictionary * mdict in sceneArray){
        if ([mdict[@"SceneID"] isEqualToString:dict[@"SceneID"]]){
            SceneName = mdict[@"SceneName"];
            break;
        }
    }
    detailVC.SceneName = SceneName;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark
#pragma mark FilterView Delegate
-(void)whileTheViewIsHidden:(NSString *)titleName andID:(NSString *)titleid isReflash:(BOOL)reflash
{
    canaddmore = NO;
    if ([mCollectionView isHeaderRefreshing]){
        [mCollectionView headerEndRefreshing];
    }
    if([mCollectionView isFooterRefreshing]){
        [mCollectionView footerEndRefreshing];
    }
    
    if(!tmpLabel){
        tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
        tmpLabel.numberOfLines = 0;
        tmpLabel.font = [UIFont systemFontOfSize:20.0f];
    }
    tmpLabel.frame = CGRectMake(0, 0, 200, 20);
    tmpLabel.text = titleName;
    [tmpLabel sizeToFit];
    
    titleIV.image = LOADIMAGE(@"downsanjiao_dark@2x");
    self.titleLabel.text = titleName;
    CGRect rect = titleIV.frame;
    rect.origin.x = 160+tmpLabel.frame.size.width/2.0f+5;
    titleIV.frame = rect;
    
    if (reflash){
        SceneID = titleid;
        page = 1;
        [self performSelector:@selector(reflashDatas) withObject:self afterDelay:0];
    }
}

#pragma mark
#pragma mark ScreenView  Delegate 
-(void)whileScreenViewIsHidden:(NSDictionary *)mdict isReflash:(BOOL)reflash
{
    
    NSString * titleName = mdict[@"SceneName"];
    NSString * titleid =mdict[@"SceneID"];
    if([titleName isEqualToString:@"年龄"]){
        titleName = @"选择年龄";
    }
    canaddmore = NO;
    if ([mCollectionView isHeaderRefreshing]){
        [mCollectionView headerEndRefreshing];
    }
    if([mCollectionView isFooterRefreshing]){
        [mCollectionView footerEndRefreshing];
    }
    
    if(!tmpLabel){
        tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
        tmpLabel.numberOfLines = 0;
        tmpLabel.font = [UIFont boldSystemFontOfSize:17.0f];
    }
    tmpLabel.frame = CGRectMake(0, 0, 200, 20);
    tmpLabel.text = titleName;
    [tmpLabel sizeToFit];
    
    titleIV.image = LOADIMAGE(@"downsanjiao_dark@2x");
    self.titleLabel.text = titleName;
    CGRect rect = titleIV.frame;
    rect.origin.x = 160+tmpLabel.frame.size.width/2.0f+2;
    titleIV.frame = rect;
    
    if (reflash){
        SceneID = titleid;
        page = 1;
        [self performSelector:@selector(reflashDatas) withObject:self afterDelay:0];
    }
}

-(void)reflashDatas
{
    [self getListDatas:1];
}

#pragma mark
#pragma mark 选择场景
-(void)chooseScene
{
    titleIV.image = LOADIMAGE(@"upicon@2x");
    
    if (mScreenView.isHidden){
        if ([self.titleLabel.text isEqualToString:@"选择年龄"]){
            mScreenView.selectName = @"年龄";
        }else{
            mScreenView.selectName = self.titleLabel.text;
        }
        [mScreenView showTheScreenView];
    }else{
        [mScreenView hiddenTheScreenView];
        titleIV.image = [UIImage imageNamed:@"downsanjiao_dark@2x"];
    }

//    [filterView showTheView];
}

#pragma mark 
#pragma mark 获取列表数据
-(void)getListDatas:(int)mPage
{
    if (![XDTools NetworkReachable]){
        page = page==1?(1):(page-1);
        [XDTools showTips:brokenNetwork toView:self.view];
        [mCollectionView headerEndRefreshing];
        [mCollectionView footerEndRefreshing];
        return;
    }

    //page 页码 pageSize 每页数据条数  SceneID 场景类别
    NSDictionary * parms = @{@"page":[NSString stringWithFormat:@"%d",mPage],
                             @"pageSize":@"10",
                             @"SceneID":SceneID};
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:works_list];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{

        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            if (page == 1){
                [dataArray removeAllObjects];
            }
            if (!tmpDict[@"data"]){
//                [XDTools showTips:tmpDict[@"msg"] toView:self.view];
//                [mCollectionView reloadData];
                page = page==1?(1):(page-1);
                [mCollectionView reloadData];
                if ([mCollectionView isHeaderRefreshing]){
                    [mCollectionView headerEndRefreshing];
                }
                if([mCollectionView isFooterRefreshing]){
                    [mCollectionView footerEndRefreshing];
                }
                return;
            }
            [dataArray addObjectsFromArray:tmpDict[@"data"][@"list"]];
            [mCollectionView reloadData];
            if ([sceneArray count]==0){     //场景分类
                [sceneArray addObjectsFromArray:tmpDict[@"data"][@"scene"]];
                mScreenView.dataArray = sceneArray;
//                filterView.dataArray = sceneArray;
            }
            canaddmore = YES;
            
            mCollectionView.backgroundColor = UIColorFromRGB(0xc7c7c7);
        }else{
            
            page = page==1?(1):(page-1);
            
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
        
        if ([mCollectionView isHeaderRefreshing]){
            [mCollectionView headerEndRefreshing];
        }
        if([mCollectionView isFooterRefreshing]){
            [mCollectionView footerEndRefreshing];
        }
        
    }];
    [request setFailedBlock:^{
        
        page = page==1?(1):(page-1);
        
        if ([mCollectionView isHeaderRefreshing]){
            [mCollectionView headerEndRefreshing];
        }
        if([mCollectionView isFooterRefreshing]){
            [mCollectionView footerEndRefreshing];
        }
        
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    if (isfirst){
        [XDTools showProgress:self.contentView];
        isfirst = NO;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
